import re
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, Alignment
from openpyxl import load_workbook

import argparse
import os
from pathlib import Path

from datetime import datetime

from tqdm import tqdm

import Log_Write

language = ["翻译字符串", "中文", "英文", "日语", "法语", "德语", "西班牙", "意大利", "俄语", "波兰",
            "土耳其语", "越南", "泰语", "印尼语", "荷兰语", "希腊语", "捷克语", "葡萄牙语", "希伯来", "瑞典语",
            "罗马尼亚语", "繁体中文", "韩", "阿拉伯", "印地语", "孟加拉语", "乌尔都语", "波斯语", "尼泊尔语", "乌克兰语",
           "马来西亚语", "斯洛伐克语"]

MAX_LINE = 100
DEFAULT_LINE = len(language)-1

def parse_arguments():
    """解析命令行参数"""
    """增强版参数解析（支持含空格路径）"""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter,
        description='多语言转换工具\n当前时间：2025-05-10 农历四月十三'
    )
    parser.add_argument(
        'input_file',
        type=Path,  # 自动转换路径对象
        help='输入文件路径（需用引号包裹含空格路径）'
    )
    parser.add_argument(
        'output_file',
        type=Path,
        help='输出文件路径'
    )
    parser.add_argument(
        '--mode',
        choices=['c2excel', 'excel2c'],
        required=True,
        help='操作模式'
    )
    parser.add_argument('--max_cols', type=int, default=DEFAULT_LINE,
                        help='Excel最大列数限制(默认31)')
    return parser.parse_args()


def c_to_excel(input_path, output_path, max_columns=MAX_LINE):
    """C语言数组转Excel"""
    data = parse_c_arrays(input_path)
    save_as_excel(data, output_path, max_columns)
    print(f"转换完成: {input_path} → {output_path}")


def excel_to_c(input_path, output_path, num_cols=DEFAULT_LINE):
    """Excel转C语言数组"""
    if(save_as_c_file(input_path, output_path, num_cols) == True):
        print(f"转换完成: {input_path} → {output_path}")
    else:
        print(f"转换失败: {input_path} → {output_path}")


def parse_c_arrays(file_path):
    """解析文件中所有符合格式的字符串数组"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 匹配所有const char* const数组定义
    arrays = re.findall(
        r'const\s*char\s*\*\s*const\s+(\w+)\s*\[\]\s*=\s*\{(.*?)\}\s*;',
        content,
        re.DOTALL
    )

    # 解析数组内容（保留原始格式）
    data = {}
    for arr_name, arr_content in arrays:
        entries = []
        for line in arr_content.split('\n'):
            line = line.strip()
            if not line or line.startswith(('//', '/*')):
                continue
            # 清理条目（保留换行符和空格）
            if '/*' in line:
                line = re.sub(r'/\*.*?\*/', '', line, flags=re.DOTALL)  # 移除块注释
            # 再处理 // 行注释
            entry = line.split('//')[0].strip().rstrip(',')
            if entry.startswith('"') and entry.endswith('"'):
                entry = entry[1:-1]  # 去引号
            if entry:
                entries.append(entry)
            else:
                entries.append("ns")
        data[arr_name] = entries

    return data


# def save_as_excel(data, output_path, max_columns=30):
#     """动态生成Excel文件"""
#     # 创建DataFrame（自动对齐长度）
#     df = pd.DataFrame.from_dict(
#         data,
#         orient='index'  # 数组名作为行
#     ).fillna('')
#
#     # 定义字体样式
#     msyh_font = Font(name='微软雅黑', size=11)  # 正文样式
#     header_font = Font(name='微软雅黑', size=12, bold=True)  # 表头样式
#
#     # 限制最大列数
#     if max_columns:
#         df = df.iloc[:, :max_columns]
#
#     # 保存Excel
#     with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
#         df.to_excel(
#             writer,
#             sheet_name='LanguageData',
#             header=[language[i+1] for i in range(df.shape[1])]
#         )
#
#         # 格式优化
#         workbook = writer.book
#         worksheet = writer.sheets['LanguageData']
#
#         # 自动换行和列宽调整
#         for row in worksheet.iter_rows():
#             for cell in row:
#                 cell.alignment  = Alignment(
#                     wrapText=True,
#                     vertical='center',
#                     horizontal='center'
#                 )
#
#         # 动态列宽（限制最大宽度30字符）
#         for col_idx, col_name in enumerate(df.columns, 1):
#             max_len = max(
#                 len(str(df.iloc[row_idx, col_idx - 1]))
#                 for row_idx in range(len(df))
#             )
#             worksheet.column_dimensions[get_column_letter(col_idx)].width = min(max_len + 2, 30)
#
#         # 冻结首行首列
#         worksheet.freeze_panes  = 'B2'

def save_as_excel(data, output_path, max_columns=MAX_LINE):  # 默认提升至100列
    """支持大列数导出的Excel生成"""
    # 动态计算实际列数（不超过max_columns）
    actual_columns = min(
        max(len(entries) for entries in data.values()),
        max_columns
    ) if max_columns else None

    # 创建DataFrame（自动填充空值）
    df = pd.DataFrame.from_dict(
        {k: v[:actual_columns] for k, v in data.items()},
        orient='index'
    ).fillna('')

    # 字体配置（微软雅黑）
    cell_font = Font(name='微软雅黑', size=11)
    header_font = Font(name='微软雅黑', size=12, bold=True)

    with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
        # 写入数据（动态生成多语言表头）
        df.to_excel(
            writer,
            sheet_name='LanguageData',
            header=[language[i + 1] for i in range(df.shape[1])]
        )

        # 格式优化
        worksheet = writer.sheets['LanguageData']

        # 批量设置样式（性能关键点）
        for row in worksheet.iter_rows():
            for cell in row:
                cell.font = cell_font
                cell.alignment = Alignment(
                    wrapText=True,
                    vertical='center',
                    horizontal='center'
                )

        # 动态列宽（限制最大50字符）
        for col_idx in range(1, df.shape[1] + 1):
            col_letter = get_column_letter(col_idx)
            max_len = max(
                len(str(cell.value))
                for cell in worksheet[col_letter]
            )
            worksheet.column_dimensions[col_letter].width = min(max_len + 2, 50)

        # 冻结窗格优化
        worksheet.freeze_panes = 'B2'


def save_as_c_file(input_excel, output_c, num_cols = MAX_LINE):
    """将Excel文件逆向转换为C语言数组"""
    # 读取Excel数据，先不限制列数
    df = pd.read_excel(input_excel,  sheet_name='LanguageData', index_col=0)
    # 动态计算实际列数
    actual_num_cols = len(df.columns)
    # 取实际列数和固定最大列数中的较小值
    valid_num_cols = min(actual_num_cols, num_cols)
    # 重新读取数据，限制列数
    df = df.iloc[:,  :valid_num_cols]

    # validate_uniqueness(df)
    if(Log_Write.log_duplicates_to_file(df) == False):
        print("检查异常！！！请查看日志")
        return False

    # 生成C文件内容
    c_code = f"/* Auto-generated from Excel on {datetime.now().strftime('%Y-%m-%d  %H:%M:%S')} */\n"
    c_code += "/* DO NOT EDIT - Generated by converter tool */\n\n"
    c_code += "\n\n# include \"NBIncludes.h\"n\n"

    c_code += """// 星期
const char * const * WeekIndexString[7] = {SunWeatherString, MonWeatherString, TueWeatherString, WedWeatherString,ThuWeatherString, FriWeatherString, SatWeatherString}; // 星期的字符串
const char * const * FullWeekIndexString[7] = {SundayString, MondayString, TuesdayString, WednesdayString, ThursdayString,FridayString, SaturdayString}; // 星期的字符串
\n"""

    # for arr_name in tqdm(df.index,  desc="处理进度", unit="行"):
    for arr_name in df.index:

        # 过滤条件：去除前后空格后不为空且不以 # 开头
        if not str(arr_name).strip() or str(arr_name)=='nan' or str(arr_name).strip().startswith('#'):
            continue

        entries = df.loc[arr_name].dropna().tolist()

        # 构建数组声明
        if(len(entries)):
            c_code += f"const char * const {arr_name}[] = {{\n"
        else:
            continue

        # 添加数组条目（自动处理转义字符）
        for entry in entries:
            escaped_entry = entry.replace('"', r'\"')  # 处理引号转义
            c_code += f'\t"{escaped_entry}",\n'

        c_code = c_code.rstrip(',\n') + ",\n};\n\n"

    # 写入C文件
    with open(output_c, 'w', encoding='utf-8') as f:
        f.write(c_code)
    return True

def validate_uniqueness(df):
    """严格唯一性验证"""
    dup_mask = df.index.duplicated(keep=False)
    if dup_mask.any():
        # 提取重复项统计（按出现频率排序）
        dup_stats = (df.index[dup_mask]
                     .value_counts()
                     .reset_index()
                     .rename(columns={'index': '重复值', 'count': '出现次数'}))

        error_msg = [
            "=" * 60,
            "log start",
            f"❌ 第一列重复值检测（当前时间：{datetime.now().strftime('%Y-%m-%d  %H:%M:%S')}）",
            f"共发现 {len(dup_stats)} 种重复值，总计 {dup_mask.sum()}  处",
            "-" * 60,
            dup_stats.to_string(index=False, justify='center'),
            "=" * 60
        ]
        raise ValueError('\n'.join(error_msg))


def FileCheck(file_path):
    try:
        os.remove(file_path)
        print(f"✅ 文件 {file_path} 已删除")
    except FileNotFoundError:
        print(f"❌ 文件 {file_path} 不存在")
    except PermissionError:
        print(f"❌ 无权限删除 {file_path}")

if __name__ == "__main__":
    args = parse_arguments()
    if args.mode == 'c2excel':
        FileCheck(args.output_file)
        c_to_excel(args.input_file, args.output_file, args.max_cols)
    elif args.mode == 'excel2c':
        FileCheck(args.output_file)
        excel_to_c(args.input_file, args.output_file, args.max_cols)
    else :
        print("args error!!!")

    # FileCheck("output\\Func_Language.xlsx")
    # c_to_excel("Func_Language.c", "output\\Func_Language.xlsx", DEFAULT_LINE)

    # FileCheck("output\\Recovered_Language.c")
    # excel_to_c("output\\Func_Language.xlsx", "output\\Recovered_Language.c", DEFAULT_LINE)